import { Input, Button, Menu, Icon, Modal } from 'antd';
const InputGroup = Input.Group;
const SubMenu = Menu.SubMenu;
import { WeaTools } from 'ecCom';
const { viewer } = WeaTools;


class PocDetail extends React.Component {
  
  state = {
    selectMenu: 0,
    current: '',
    openKeys: [],
    treeData: [],
    title: '',
    bqlist: [],
    czsm: '',
    isScroll: false,
    offsetTopList: []
  }

  componentDidMount() {
		this.getDetail();

    let h = $('#container').height() - $('.menu').offset().top
    $('.menu').css({ minHeight: h + 'px', position: 'relative' })
    document.querySelector('#container').onscroll = (event) => {
      let { offsetTopList } = this.state;
      let top = 0
      let h1 = $('#container').height() - $('.menu').offset().top
      if (document.querySelector('#container').scrollTop > 360) {
        top = document.querySelector('#container').scrollTop - 360
        // $('.menu').css({ minHeight: window.innerHeight + 'px' })
        $('.menu').css({ position: 'fixed', top: 0, height: '100%' })
        $('.content').css({ marginLeft: '168px' })
      } else {
        top = 0
        // $('.menu').css({ minHeight: h1 + 'px' })
        $('.menu').css({ position: 'relative', minHeight: h1 + 'px' })
        $('.content').css({ marginLeft: 0 })
      }
      // $('.menu').css({ position: 'relative', top: top + 'px' })


      let arr = JSON.parse(JSON.stringify(offsetTopList))
      try {
          arr.reverse().forEach((item, i)=> {
            if (document.querySelector('#container').scrollTop + $('body').height() / 2 >= item) {
              this.setState({
                current: (offsetTopList.length - 1 - i) + '',
              });
              throw new Error('LoopInterrupt');
            }
            this.setState({
              current: '0',
            });
          })
      } catch (e) {
        if (e.message !== "LoopInterrupt") throw e
      }

    }
  }

  getDetail() {
    const URL = '/plugin/demoDev/demoCenter/demoCenter_v1.jsp?operation=detail&tableid=2494&demoType=poc&id=' + this.getQueryVariable(window.location.href, 'id');
		WeaTools.callApi(URL, 'GET')
      .then(( {datas} ) => {
        this.setState({
          title: datas.demoname,
          bqlist: datas.bqList,
          czsm: datas.czsm
        });
        document.title = datas.demoname
        document.querySelector('#poccontent').innerHTML = datas.ldms
        setTimeout(() => {
          var headings = document.querySelectorAll("h1,h2,h3,h4,h5,h6")
          var arr = Array.from(headings).map((item,index) => {
            item.setAttribute('id','bt_'+index)
            item.setAttribute('class','yjbt')
            return {
              key: index,
              text: item.innerText,
              nodeName: item.nodeName,
              hLevel: Number(item.nodeName.split('H')[1])
            }
          })
          var treeData = this.calcMenu(arr);
          this.setState({
            treeData: treeData,
          });
          $('#poccontent *').css({maxWidth: '100%'});
          $('#poccontent img').css({height: 'auto' , cursor: 'zoom-in'});
          
          $('#poccontent img').each((i,v) => {
            $(v).attr('data-imgsrc', $(v).attr('src'))
            $(v).attr('class', 'formImgPlay')
            $(v).click((event) => {
              viewer(event)
            })
          })
        })

        setTimeout(() => {
          var offsetTopList = []
          $('#poccontent .yjbt').each((i,v) => {
            console.log($(v).offset(),$(v))
            offsetTopList.push(parseInt($(v).offset().top))
          })
          this.setState({
            offsetTopList: offsetTopList,
          });
        },500)
      }).catch((err) => {
 console.log(err) 
})
  }

  // 计算左侧菜单
  calcMenu(flatArr){
    var tree = [];
    var copyArr = flatArr.map(function (item) {
 return item; 
});
    // 根据指定级别查找该级别的子孙级，并删除掉已经查找到的子孙级
    var getChildrenByLevel = function (currentLevelItem, arr, level) {
      if(!currentLevelItem){
        return;
      }
      // 将level值转成负数，再进行比较
      var minusCurrentLevel = -currentLevelItem.hLevel;
      var children = [];
      for(var i = 0, len = arr.length; i < len; i++){
        var levelItem = arr[i];
        if(-levelItem.hLevel < minusCurrentLevel){
          children.push(levelItem);
        }else { // 只找最近那些子孙级
          break;
        }
      }
      // 从数组中删除已经找到的那些子孙级，以免影响到其他子孙级的查找
      if(children.length > 0){
        arr.splice(0, children.length);
      }
      return children;
    }
    var getTree = function (result, arr, level) {
      // 首先将数组第一位移除掉，并添加到结果集中
      var currentItem = arr.shift();
      currentItem.level = level;
      result.push(currentItem);
      while (arr.length > 0){
        if(!currentItem){
          return;
        }
        // 根据当前级别获取它的子孙级
        var children = getChildrenByLevel(currentItem, arr, level);
        // 如果当前级别没有子孙级则开始下一个
        if(children.length == 0){
          currentItem = arr.shift();
          currentItem.level = level;
        if(currentItem){
          result.push(currentItem);
        }
        continue;
        }
        currentItem.children = [];
        // 查找到的子孙级继续查找子孙级
        getTree(currentItem.children, children, level + 1);
      }
    }
    getTree(tree, copyArr, 1);
    return tree;
  }

  selectMenus (data) {
    const { czsm } = this.state;
    this.setState({
      selectMenu: data,
    });
    setTimeout(() => {
      if (document.querySelector('#czsm')) document.querySelector('#czsm').innerHTML = czsm
    })
  }

  handleClick(e) {
    let h = document.querySelector(`#bt_${e.key}`).offsetTop
    if (h) document.querySelector('#container').scrollTop = h
    this.setState({
      current: e.key,
    });
  }

  getQueryVariable(url, variable){
    var query = url.split("?")[1];
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
      if(pair[0] == variable) return pair[1]; // 没有花括号默认执行第一个js语句
    }
    return(false);
  }

  renderMenuItem(navList) {
    return navList.map((item, index) => {
      if(item.children && item.children.length){
        return (<SubMenu key={item.key } title={<span style={{ fontSize: '14px', fontFamily: 'PingFang SC', fontWeight: 500, color: '#000000', marginLeft: '9px'}}>{item.text}</span>}>
          { this.renderMenuItem(item.children) }
        </SubMenu> )
      }
      return (<Menu.Item key={item.key } onClick={() => {
 window.history.push(item.path) 
}}>
        <span style={{ fontSize: '14px', fontFamily: 'PingFang SC', fontWeight: 500, color: '#000000', marginLeft: '9px'}}>{item.text}</span>
      </Menu.Item>)
    })
  }

  onToggle(info) {
    this.setState({
      openKeys: info.open ? info.keyPath : info.keyPath.slice(1),
    });
  }

  render() {
    const { selectMenu, current, openKeys, treeData, title, bqlist, czsm } = this.state;
    return (
      <div id="pocdetail">
        <div className="header">
          <div className="header-left">
            <img src={require('../imgs/logo.png')} />
          </div>
          <div className="header-right">
            <div className="xq" onClick={ () => {
 window.open('https://www.e-cology.com.cn/spa/develop/static/index.html#/main/develop/demo/demoListPersonal')
} }>
              <img src={require('../imgs/xqfx.png')} />
              <span>DEMO需求评估</span>
            </div>
            <div className="yun" onClick={ () => {
 window.open('https://www.e-cology.com.cn/spa/workflow/static4form/index.html#/main/workflow/req?iscreate=1&workflowid=2159')
} }>
              <img src={require('../imgs/yun.png')} />
              <span>云资源申请</span>
            </div>
            
          </div>
        </div>
        <div className="poc-topbg" style={{ backgroundImage: 'url(' + require('../imgs/pocdetailbg.png') + ')' }}>
          <div className="poc-topbg-con">
            <p>{title}</p>
            <div className="poc-topbg-bq-container">
              {
                bqlist.map((v) => (
                  <div>{v}</div>
                ))
              }
            </div>
          </div>
          <div className="poc-topbg-menu">
            <div>
              <div onClick={ () => this.selectMenus(0) } className={`menu-cell ${selectMenu == 0 ? 'active-menu' : ''}` }>内容概述</div>
              <div onClick={ () => this.selectMenus(1) } className={`menu-cell ${selectMenu == 1 ? 'active-menu' : ''}` }>操作说明</div>
            </div>
          </div>
        </div>
        <div className="poc-main" style={selectMenu == 1 ? {display: 'none'} : {}}>
          <div className="menu" id="TOC">
            <Menu onClick={ (e) => this.handleClick(e) }
              style={{ width: 240 }}
              selectedKeys={[current]}
              onOpen={ (e) => this.onToggle(e)}
              onClose={ (e) => this.onToggle(e)}
              openKeys={openKeys}
              mode="inline">
                {
                    treeData.map((item, index) => {
                      if(item.children && item.children.length){
                        return (<SubMenu key={item.key } title={<span style={{ fontSize: '14px', fontFamily: 'PingFang SC', fontWeight: 500, color: '#000000', marginLeft: '9px'}}>{item.text}</span>}>
                          { this.renderMenuItem(item.children) }
                        </SubMenu> )
                      }
                      return ( <Menu.Item key={item.key} onClick={() => {
 window.history.push(item.path) 
}}><span style={{ fontSize: '14px', fontFamily: 'PingFang SC', fontWeight: 500, color: '#000000', marginLeft: '9px'}}>{item.text}</span>
                      </Menu.Item>)
                    })
                }
            </Menu>
          </div>
          <div className="content">
            <div id="poccontent"></div>
          </div>
        </div>
        <div className="main1" style={selectMenu == 0 ? {display: 'none'} : {}}>
        {
          czsm ? <div id="czsm"></div> : <div><img className="nodata" src={require('../imgs/nodata.png')} /></div>
        }
          
        </div>
      </div>
    )
  }
}

export default PocDetail